import store from '@/store'
import _ from 'lodash'

/**
 * 直接设置model值
 *
 * 执行方式:
 *    modelSet('app.userInfo.name','vue') 调用store/index.js中modelSet
 *    modelSet('app','userInfo.name','vue') 调用store/modules/---.js中modelSet
 *
 * @param p0
 * @param p1
 * @param p2
 */
export function modelSet(p0, p1, p2) {
  if (arguments.length === 2) {
    let path = p0
    let data = p1
    store.commit(`modelSet`, { path, data })
  } else if (arguments.length === 3) {
    let moduleName = p0
    let path = p1
    let data = p2
    store.commit(`${moduleName}/modelSet`, { path, data })
  }
}

/*
* 获取model中的值
* this.modelGet('wxInfo.openid')
* */
export function modelGet(p0, p1) {
  if (arguments.length === 1) {
    let path = p0
    return _.get(store.state, path)
  } else if (arguments.length === 2) {
    let moduleName = p0
    let path = p1
    return _.get(store.state, `${moduleName}.${path}`)
  }
}


export async function modelSetWithServer(p0, p1, p2) {
  let moduleName = p0
  let path = p1
  let data = p2

  if (/\./.test(p0)) {
    let moduleNameArr = p0.split('.')
    moduleName = moduleNameArr.shift()
    path = moduleNameArr.join('.')
    data = p1
  }

  try {
    let res = await store.dispatch(`${moduleName}/modelSetWithServer`, { path, data })
    return res
  } catch (e) {
    return Promise.reject(e)
  }
}

/*
const actions = {
  async modelSetWithServer({ commit, state }, payload) {
    try {
      let response = {}
      switch (payload.path) {
        case 'teacherInfo':
          response = await util.requestGet('/api/user/teacherInfo', payload.data)
          break
        case 'list':
          response = await util.requestGet('/api/user/list', payload.data)
          break
      }
      commit('modelSet', { path: payload.path, data: response.data })
      return response
    } catch (e) {
      return Promise.reject(e)
    }
  },
}
const mutations = {
  modelSet: (state, payload) => {
    _.set(state, payload.path, payload.data)
  },
}
* */

/*
* 使用方法
*   传三个参数,与两个参数效果一致,在内容进行了分隔处理
*     modelSet('app.userInfo.name','vue')
*     modelSet('app','userInfo.name','vue')
*
*     modelSetWithServer('app.userInfo.name','vue')
*     modelSetWithServer('app','userInfo.name','vue')
* */
